#include <iostream>
#include "CBufferedStream.h"

using namespace std;

int main(int argc,char *argv[])
{

	if(argc<2) {
		cout << "Usages : " << argv[0] << " -f <file> or -p" << endl;
		exit(-1);
	}


	if(strcmp(argv[1],"-f")==0) {
		CBufferedStream buf(argv[2]);
		istream is(&buf);

		long first = buf.tellg();

		char line[MAX_BUF_SIZE];
		while(!is.eof()) {
			if(!is.getline(line,MAX_BUF_SIZE,'\n').fail()) {
				long next = buf.tellg();
				long current = next;

				// skip '\n'
				--current;
				do {
					buf.seekg(--current);
					char c;
					if(!is.get(c).fail()) cout << c;
				} while(first<current);
				cout << endl;

				first = next;
				buf.seekg(first);
			}
		}
	}

	else if(strcmp(argv[1],"-p")==0) {
		streambuf *buff = cin.rdbuf();
		istream is(buff);

		char line[MAX_BUF_SIZE];
		while(!is.eof()) {
			if(!is.getline(line,MAX_BUF_SIZE,'\n').fail()) cout << line << endl;
			else {
				cout << line << endl; 
				is.clear();
			}
		}
	}
}
